<template>
  <!-- ✅ 必须有一个根元素 -->
  <div class="hot-problem-detail-container">
    <!-- 头部组件 -->
    <Header @open-question-modal="showQuestionModal = true" />

    <!-- 问题详情 -->
    <div class="question-detail">
      <h1 class="question-title">{{ questionname }}</h1>
      <span class="question-description">{{ questiondesc }}</span>
      <div> <button class="Writeanswer" @click="editShow">{{ btnTxt }}</button></div>
    </div>


    <!-- 写回答-->
    <div class="showedit" v-show="isshowedit">
      <vue-editor v-model="Articleeditor"></vue-editor>
    </div>
    <div><button v-show="buttonIsshow" class="Writeanswer" @click="SaveContent">保存</button></div>
    <!-- <button class="Writeanswer" @click="getQuestion">测试</button>-->


    <!-- 提问模态框 -->
    <div class="modal-bg" v-show="showQuestionModal">
      <span class="message" v-if="message">{{ message }}</span>
      <div class="modal">
        <textarea v-model="newQuestionTitle" class="Toaskinput" placeholder="请输入你提的问题" />
        <textarea v-model="newQuestionDesc" class="Toaskinput" placeholder="请输入问题描述" />
        <button class="toquesionask" @click="submitQuestion">提问</button>
        <button class="toquesionask" @click="closeModal">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import Header from './Header.vue';
import http from '@/api/http'; // ✅ 修复：导入 http
import { VueEditor } from 'vue2-editor';
const { TextDecoder } = globalThis;
// ✅ 正确导入 fflate 的同步方法
import { deflateSync } from 'fflate';
export default {
  name: 'HotProblemDetail',
  components: {
    Header,
    VueEditor
  },
  data() {
    return {
      // ✅ 保留必要的数据
      Articleeditor: '',
      newQuestionTitle: '',
      newQuestionDesc: '',
      message: '',
      showQuestionModal: false,// 控制模态框显示,
      isshowedit: false,
      buttonIsshow: false,
      questionname: '',
      questiondesc: '',
      btnTxt: '写回答',
      // ❌ 删除无用变量：activeTab, searchQuery
    };
  },

  async created() { // 或者 mounted
    await this.getQuestion(); // 可选：等待数据加载完成再继续
  },
  methods: {
    //解压字符串
    


    async getQuestion() {
      const id = this.$route.query.qid;
      const response = await http.post('/api/Essay/GetQuestionsById', {
        Id: id,
      });
      console.log("response.data[0]");
      console.log(response.data[0]);
      this.questionname = response.data[0].question;
      this.questiondesc = response.data[0].problemDescription;


      console.log(this.questionname);
      const responseAnswer = await http.post('/api/Essay/AnswerShowByUserid', {
        UserId: response.data[0].userId,
        QuestionName: this.questionname
      });
      if (responseAnswer.data[0].answerContent != '' && response.data[0].userId != '') {

        this.btnTxt = '查看我的回答';
     // var cczip=  this.decompressString( responseAnswer.data[0].answerContent);
        console.log("responseAnswer.data[0].answerContent");
        console.log(responseAnswer.data[0].answerContent);
        this.Articleeditor =responseAnswer.data[0].answerContent//cczip// responseAnswer.data[0].answerContent;
      }
      console.log()
    },
    // ✅ 关闭模态框
    closeModal() {
      this.showQuestionModal = false;
      this.newQuestionTitle = '';
      this.newQuestionDesc = '';
    },
    editShow() {
      this.isshowedit = true;
      this.buttonIsshow = true;
    },
    SaveContent() {

      // 关闭 UI
      this.isshowedit = false;
      this.buttonIsshow = false;

      // 获取 qid
      const qid = this.$route.query.qid;

      // 内容校验
      if (!this.Articleeditor || typeof this.Articleeditor !== 'string') {
        console.warn('文章内容为空或格式不正确');
        return;
      }

      // 编码为 Uint8Array
      const encoder = new TextEncoder();
      const uint8 = encoder.encode(this.Articleeditor);

      // ✅ 使用 deflateSync（同步）—— 不需要 callback
      const compressed = deflateSync(uint8, { level: 9 });

      // 转为 Base64
      let binary = '';
      for (let i = 0; i < compressed.length; i++) {
        binary += String.fromCharCode(compressed[i]);
      }
      const zipData = btoa(binary);
      console.log("questionname" + this.questionname);
      console.log("压缩数据:", zipData);
      const sid = JSON.parse(localStorage.getItem('user') || '{}').sid;
      const response = http.post('/api/Essay/AnswerAdd', {
        "userid": sid,
        "question": this.questionname,
        "answerContent": zipData
      });
      this.Articleeditor = '';


    },
    // ✅ 提交问题
    submitQuestion() {
      const user = JSON.parse(localStorage.getItem('user'));

      if (!this.newQuestionTitle.trim() || !this.newQuestionDesc.trim()) {
        this.message = '请填写完整内容';
        setTimeout(() => { this.message = ''; }, 2000);
        return;
      }

      // 使用导入的 http
      http.post('/api/Essay/AddQuestions', {
        questionname: this.newQuestionTitle,
        questioner: user.name,
        questionerid: user.sid,
        questiondesc: this.newQuestionDesc
      })
        .then(response => {
          this.message = response.message;
          console.log("✅ 请求成功：", response.message);
          setTimeout(() => { this.message = ''; }, 2000);
          // 提交成功后关闭模态框
          this.closeModal();
        })
        .catch(error => {
          this.message = error.message || '提交失败，请重试';
          console.log("❌ 请求失败：", error.message);
          setTimeout(() => { this.message = ''; }, 2000);
        });
    }
  }
};
</script>

<style scoped>
.showedit {
  width: 70%;
  margin-left: 15%;
  background-color: white;

}

.Writeanswer {
  margin-right: 54%;
  background: none;
  background: none;
  border: 1px solid;
  border-radius: 3px;
  color: #8491a5;
  color: blue;
  cursor: pointer;
  display: inline-block;
  font-size: 14px;
  line-height: 32px;
  padding: 0 16px;
  text-align: center;

}



/* ✅ 根容器 */
.hot-problem-detail-container {
  min-height: 100vh;
  position: relative;
}

/* 问题详情样式 */
.question-detail {
  width: 65%;
  margin: 140px auto 0;
  padding: 20px;

  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.question-title {
  margin-right: 45%;
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.question-description {
  margin-right: 45%;
  font-size: 16px;
  color: #666;
  line-height: 1.6;
}

/* ========== 模态框样式（保持不变）========== */
.Toaskinput {
  border: none;
  outline: none;
  width: 80%;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  min-height: 80px;
}

.modal-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  padding: 30px;
  border-radius: 10px;
  min-width: 800px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.toquesionask {
  background-color: #1579DC;
  color: white;
  width: 120px;
  height: 40px;
  border: none;
  border-radius: 35px;
  cursor: pointer;
  font-size: 16px;
  margin-top: 10px;
}

.toquesionask:hover {
  background-color: #0a5cb7;
}

.message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 10px 15px;
  background-color: #1976D2;
  color: white;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  z-index: 1001;
  font-size: 14px;
}
</style>